package linuxbox.news.servlet;

import javax.servlet.http.*;
import org.apache.log4j.Logger;

import linuxbox.common.*;

public class BoxNewsSettingsAction extends Action {
    protected static Logger logger = Logger
            .getLogger(BoxNewsSettingsAction.class.getName());
    protected static String viewJSP = null;
    protected static String editJSP = null;

    public void doAction(HttpSession aSession, BoxSession aBoxSession,
            HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String str = req.getParameter("SubmitCancel");
        if (str != null) {
            sendFile(viewJSP, req, resp);
            return;
        }

        str = (String) req.getParameter("SubmitEdit");
        if (str != null) {
            GetSettings(req, aBoxSession);
            sendFile(editJSP, req, resp);
            return;
        }
        str = (String) req.getParameter("SubmitSave");
        if (str != null) {
            SaveSettings(req, aBoxSession);
            sendFile(viewJSP, req, resp);
            return;
        }

        sendFile(viewJSP, req, resp);
    }

    protected void SaveSettings(HttpServletRequest req, BoxSession session) {
        try {
            String str = req.getParameter("ENTRIES_PER_PAGE");
            session.setConfigInt("news", "General", "Entries Per Page", Integer
                    .parseInt(str));

            str = req.getParameter("ENTRIES_PER_HOMEPAGE");
            session.setConfigInt("news", "HomePage", "Entries Per HomePage",
                    Integer.parseInt(str));

            str = req.getParameter("LENGTH");
            session.setConfigInt("news", "HomePage", "Length", Integer
                    .parseInt(str));
        } catch (Exception e) {
            // TODOXX: if input data error, should forward to the error page
            if (logger.isDebugEnabled()) {
                logger.error(e);
            }
        }
    }

    protected void GetSettings(HttpServletRequest req, BoxSession session) {
        try {
            int i = session.getConfigInt("news", "General", "Entries Per Page");
            req.setAttribute("ENTRIES_PER_PAGE", String.valueOf(i));

            i = session
                    .getConfigInt("news", "HomePage", "Entries Per HomePage");
            req.setAttribute("ENTRIES_PER_HOMEPAGE", String.valueOf(i));

            i = session.getConfigInt("news", "HomePage", "Length");
            req.setAttribute("LENGTH", String.valueOf(i));
        } catch (Exception e) {
            if (logger.isDebugEnabled()) {
                logger.error(e);
            }
        }
    }

    public void setViewJSP(String str) {
        viewJSP = str;
    }

    public void setEditJSP(String str) {
        editJSP = str;
    }
}
